<template>
  <el-dialog
    v-model="dialogVisible"
    :title="form.id ? '编辑企业账单汇总' : '新增企业账单汇总'"
    width="600px"
    append-to-body
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="企业" prop="companyId">
        <el-select
          v-model="form.companyId"
          placeholder="请选择企业"
          style="width: 100%"
          filterable
          :disabled="!!form.id"
        >
          <el-option
            v-for="company in companyOptions"
            :key="company.id"
            :label="company.companyName"
            :value="company.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="委托开始时间" prop="entrustStartDate">
        <el-date-picker
          v-model="form.entrustStartDate"
          type="month"
          placeholder="请选择委托开始时间"
          value-format="YYYY-MM"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="委托结束时间" prop="entrustEndDate">
        <el-date-picker
          v-model="form.entrustEndDate"
          type="month"
          placeholder="请选择委托结束时间"
          value-format="YYYY-MM"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="服务时长(月)" prop="serviceDurationMonths">
        <el-input-number
          v-model="form.serviceDurationMonths"
          :min="1"
          :max="120"
          style="width: 100%"
          placeholder="请输入服务时长"
        />
      </el-form-item>

      <el-form-item label="收费总金额" prop="totalAmount">
        <el-input-number
          v-model="form.totalAmount"
          :min="0"
          :precision="2"
          style="width: 100%"
          placeholder="请输入收费总金额"
        />
      </el-form-item>

      <el-form-item label="开票状态" prop="invoiceStatus">
        <el-select v-model="form.invoiceStatus" placeholder="请选择开票状态" style="width: 100%">
          <el-option label="未开票" value="0" />
          <el-option label="已开票" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="开票信息" prop="invoiceInfoId">
        <el-input
          v-model="invoiceInfoName"
          placeholder="暂无开票信息"
          style="width: 100%"
          disabled
        />
      </el-form-item>

      <el-form-item label="收款信息" prop="collectionInfoId">
        <el-input
          v-model="collectionInfoName"
          placeholder="暂无收款信息"
          style="width: 100%"
          disabled
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="EnterpriseBillSummaryForm">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { saveEnterpriseBillSummaryApi, getEnterpriseBillSummaryApi } from '@/api/oa/enterprisebillsummary'
import { AccountingCompaniesApi } from '@/api/oa/accountingcompanies'
import type { EnterpriseBillSummarySaveReqVO, EnterpriseBillSummaryVO } from '@/api/oa/enterprisebillsummary'

defineOptions({ name: 'EnterpriseBillSummaryForm' })

const emit = defineEmits<{
  success: []
  close: []
}>()

const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive<EnterpriseBillSummarySaveReqVO>({
  id: undefined,
  companyId: 0,
  entrustStartDate: '',
  entrustEndDate: '',
  serviceDurationMonths: 1,
  totalAmount: 0,
  invoiceStatus: '0',
  invoiceInfoId: undefined,
  collectionInfoId: undefined
})

// 表单验证规则
const rules = {
  companyId: [{ required: true, message: '请选择企业', trigger: 'change' }],
  entrustStartDate: [{ required: true, message: '请选择委托开始时间', trigger: 'change' }],
  entrustEndDate: [{ required: true, message: '请选择委托结束时间', trigger: 'change' }],
  serviceDurationMonths: [{ required: true, message: '请输入服务时长', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '请输入收费总金额', trigger: 'blur' }],
  invoiceStatus: [{ required: true, message: '请选择开票状态', trigger: 'change' }]
}

// 选项数据
const companyOptions = ref<any[]>([])
const invoiceOptions = ref<any[]>([])
const collectionOptions = ref<any[]>([])

// 显示名称
const invoiceInfoName = ref('')
const collectionInfoName = ref('')

// 打开对话框
const open = async (data?: EnterpriseBillSummaryVO) => {
  dialogVisible.value = true
  
  if (data) {
    // 编辑模式
    const detail = await getEnterpriseBillSummaryApi(data.id)
    
    // 直接设置当前企业信息到下拉框选项
    companyOptions.value = [{
      id: detail.companyId,
      companyName: detail.companyName
    }]
    
    Object.assign(form, {
      id: detail.id,
      companyId: detail.companyId,
      entrustStartDate: detail.entrustStartDate,
      entrustEndDate: detail.entrustEndDate,
      serviceDurationMonths: detail.serviceDurationMonths,
      totalAmount: detail.totalAmount,
      invoiceStatus: detail.invoiceStatus,
      invoiceInfoId: detail.invoiceInfoId,
      collectionInfoId: detail.collectionInfoId
    })
    
    // 设置显示名称
    invoiceInfoName.value = detail.invoiceInfoDetail || '暂无开票信息'
    collectionInfoName.value = detail.collectionInfoDetail || '暂无收款信息'
  } else {
    // 新增模式 - 加载所有企业列表
    await loadOptions()
    resetForm()
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    companyId: 0,
    entrustStartDate: '',
    entrustEndDate: '',
    serviceDurationMonths: 1,
    totalAmount: 0,
    invoiceStatus: '0',
    invoiceInfoId: undefined,
    collectionInfoId: undefined
  })
  
  // 重置显示名称
  invoiceInfoName.value = ''
  collectionInfoName.value = ''
  
  formRef.value?.clearValidate()
}

// 加载选项数据
const loadOptions = async () => {
  try {
    // 加载企业列表
    const companies = await AccountingCompaniesApi.getAllValidCompanies()
    companyOptions.value = companies.map((company: any) => ({
      id: company.id,
      companyName: company.companyName
    }))
  } catch (error) {
    console.error('加载选项数据失败:', error)
    ElMessage.error('加载选项数据失败')
  }
}



// 提交表单
const handleSubmit = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  // 验证时间范围
  if (form.entrustStartDate && form.entrustEndDate) {
    if (form.entrustStartDate > form.entrustEndDate) {
      ElMessage.error('委托开始时间不能晚于委托结束时间')
      return
    }
  }

  loading.value = true
  try {
    await saveEnterpriseBillSummaryApi(form)
    ElMessage.success(form.id ? '更新成功' : '创建成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
  emit('close')
}

// 监听委托时间变化，自动计算服务时长
watch([() => form.entrustStartDate, () => form.entrustEndDate], ([startDate, endDate]) => {
  if (startDate && endDate && startDate <= endDate) {
    const start = new Date(startDate + '-01')
    const end = new Date(endDate + '-01')
    const months = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth()) + 1
    form.serviceDurationMonths = Math.max(1, months)
  }
})

// 暴露方法
defineExpose({
  open
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.text-gray-500 {
  color: #6b7280;
}

.text-sm {
  font-size: 0.875rem;
}

.mt-1 {
  margin-top: 0.25rem;
}
</style> 